<template>
  <div class="container">
    <div class="header">
      <div class="selected">
        <van-field
          v-model="shipLock"
          is-link
          arrow-direction="down"
          readonly
          label=""
          placeholder="请选择"
          @click="showPicker = true"
        />
        <van-popup v-model:show="showPicker" round position="bottom">
          <van-picker
            title="选择船闸"
            :columns="shipLockOptions"
            :columns-field-names="customFieldName"
            @cancel="showPicker = false"
            @confirm="confirmShipLock"
          />
        </van-popup>
      </div>          
    </div>
    <div class="tab">
      <van-tabs 
        v-model:active="tabActive" 
        swipe-threshold="3"
        @click-tab="onClickTab"
      >
        <van-tab title="基本信息">
          <div class="basic-info">
            <div class="item">
              <div class="name">船闸名称</div>
              <div class="value">{{ baseInfoObj.name }}</div>
            </div>
            <div class="item">
              <div class="name">所属航道</div>
              <div class="value">{{ baseInfoObj.channel }}</div>
            </div>             
            <div class="item">
              <div class="name">管理单位</div>
              <div class="value">{{ baseInfoObj.manage }}</div>
            </div>
            <div class="item">
              <div class="name">船闸等级</div>
              <div class="value">{{ baseInfoObj.slLevel }}</div>
            </div>
            <!-- <div class="item">
              <div class="name">当年变形预警情况</div>
              <div class="value">{{ baseInfoObj.alertSit }}</div>
            </div> -->
            <!-- <div class="item">
              <div class="name">安全评定等级</div>
              <div class="value">{{ baseInfoObj.saveLvl || "--"}}</div>
            </div> -->
            <!-- <div class="item">
              <div class="name">监测周期</div>
              <div class="value">{{ baseInfoObj.cyc }}</div>
            </div> -->
            <div class="item">
              <div class="name">建成年份</div>
              <div class="value">{{ baseInfoObj.createYear }}</div>
            </div>
            <div class="item">
              <div class="name">已使用年限</div>
              <div class="value">{{ baseInfoObj.useYear }}</div>
            </div>
          </div>
        </van-tab>
        <van-tab title="过闸船舶统计分析">   
          <div style="margin: 20px 16px;">
            <van-field
              v-model="year"
              is-link
              arrow-direction="down"
              readonly
              label=""
              placeholder="请选择"
              @click="showYearPicker = true"
            />
            <van-popup v-model:show="showYearPicker" round position="bottom">
              <van-date-picker
                v-model="currentDate"
                title="请选择"
                :min-date="new Date(2021, 0, 1)"
                :max-date="new Date()"
                :columns-type="columnsType"
                @cancel="showYearPicker = false"
                @confirm="confirmYear"
              />
            </van-popup>
          </div>       
          <div class="content">
            <div class="title">北江船闸过闸船舶货物吨位统计分析</div>
            <div class="count">
              <div class="item">
                <span class="name">总上行船舶数</span>
                <span class="value">{{ totalUpShipNum }}艘</span>
              </div>
              <div class="item">
                <span class="name">总下行船舶数</span>
                <span class="value">{{ totalDownShipNum }}艘</span>
              </div>
            </div>
            <div id="stackedChart" style="height: 200px;"></div>
          </div>
          <div style="margin: 20px 16px;">
            <van-field
              v-model="date1"
              is-link
              arrow-direction="down"
              readonly
              label=""
              placeholder="请选择日期"
              @click="showCalendar1 = true"
              style="width: 100%;"
            />
            <van-calendar v-model:show="showCalendar1" type="range" @confirm="confirmDate1" :min-date="new Date(2021, 3, 6)" :max-date="new Date()" :allow-same-day="true" />
          </div>
          <div class="content">
            <div class="title">北江船闸过闸船舶货物类型统计分析</div>
            <div id="pieChart" style="height: 200px;"></div>
            <div class="pie-table">
              <div class="pie-tbody">
                <div class="pie-tr" v-for="(item,index) in pieChartData" :key="index">
                  <div style="display: flex;align-items: center;width: 40%;">
                    <div class="li" :style="`background:${item.itemStyle?item.itemStyle.color:''}`"></div>
                    <div class="pie-td">{{ item.name }}</div>
                  </div>     
                  <div class="pie-td" style="width: 30%;">{{ item.load }}吨</div>  
                  <div class="pie-td" style="width: 30%;">{{ item.value }}%</div>
                </div>
              </div>
            </div>
          </div>
        </van-tab>
        <!-- <van-tab title="变形监测分析">
          <div class="btn-group">
            <div class="btn" :class="currentActive === 1? 'active' : ''" @click="currentActiveChange(1)" style="margin-right: 10px;">多点单周期图</div>
            <div class="btn" :class="currentActive === 2? 'active' : ''" @click="currentActiveChange(2)">单点多周期图</div>
          </div>
          <div class="content"> 
            <div class="filter">
              <template v-if="currentActive === 1">
                <van-field
                  is-link
                  arrow-direction="down"
                  readonly
                  label=""
                  placeholder="周期"
                  style="width: 30%;"
                />
                <van-field
                  v-model="cycle"
                  is-link
                  arrow-direction="down"
                  readonly
                  label=""
                  placeholder="请选择周期"
                  style="width: 40%;"    
                  @click="showCycle('cycle')"              
                />                
              </template>   
              <template v-if="currentActive === 2">
                <div style="display: flex;flex-wrap: wrap">
                  <van-field
                    v-model="pointName"
                    is-link
                    arrow-direction="down"
                    readonly
                    label=""
                    placeholder="请选择点"
                    @click="!pointNameData.length? showToast('暂无数据') : showPointPicker = true"
                    style="width: 50%;"
                  />
                  <van-field
                    v-model="singleType"
                    is-link
                    arrow-direction="down"
                    readonly
                    label=""
                    placeholder="请选择类型"
                    @click="showTypePicker = true"
                    style="width: 50%;"
                  />
                  <van-field
                    v-model="singleValue1"
                    is-link
                    arrow-direction="down"
                    readonly
                    label=""
                    placeholder="请选择周期"
                    v-if="singleType === '周期'"
                    @click="showCycle('singleValue1')"   
                    style="width: 50%;" 
                  />
                  <van-field
                    v-model="singleValue2"
                    is-link
                    arrow-direction="down"
                    readonly
                    label=""
                    placeholder="请选择周期"
                    v-if="singleType === '周期'"
                    @click="showCycle('singleValue2')"   
                    style="width: 50%;"
                  />
                  <van-field
                    v-model="singleTime"
                    is-link
                    arrow-direction="down"
                    readonly
                    label=""
                    placeholder="请选择时间"
                    v-if="singleType === '时间'"
                    @click="showCalendar = true"
                    style="width: 100%;"
                  />
                </div>
                
                <van-popup v-model:show="showPointPicker" round position="bottom">
                  <van-picker
                    title=""
                    :columns="pointNameData"
                    @cancel="showPointPicker = false"
                    @confirm="confirmPoint"
                  />
                </van-popup>
                <van-popup v-model:show="showTypePicker" round position="bottom">
                  <van-picker
                    title=""
                    :columns="singleTypeData"
                    @cancel="showTypePicker = false"
                    @confirm="confirmType"
                  />
                </van-popup>
                <van-calendar 
                  v-model:show="showCalendar" 
                  type="range" 
                  @confirm="onConfirmCalendar" 
                  :min-date="new Date(new Date().getTime()- 60 * 24 * 3600 * 1000)" 
                  :max-date="new Date()"
                />
              </template>    
              <van-popup v-model:show="showCyclePicker" round position="bottom">
                <van-picker
                  title="选择周期"
                  :columns="cycleOptions"
                  :columns-field-names="cycleFieldName"
                  @cancel="showCyclePicker = false"
                  @confirm="confirmCycle"
                />
              </van-popup>                     
            </div>            
            <div id="lineChart1" style="height: 300px;"></div>             
          </div>            
        </van-tab> -->        
        <!-- <van-tab title="闸坝情况记录">
          <div class="content">
            <div class="record">
              <div class="item" @click.prevent="showToast('暂无数据')">
                <div class="name">
                  <img src="../../static/images/icon-record-two.png" alt="">
                  <div>日常维护记录</div>
                </div>
                <div><img src="../../static/images/icon-record-arrow.png" alt=""></div>
              </div>
            </div>
            <div class="record">
              <div class="item" @click.prevent="handleGo">
                <div class="name" >
                  <img src="../../static/images/icon-record-three.png" alt="">
                  <div>船闸操作记录</div>                
                </div>
                <div><img src="../../static/images/icon-record-arrow.png" alt=""></div>
              </div>
            </div>
            <div class="record">
              <div class="item" @click="isShow2 = !isShow2">
                <div class="name">
                  <img src="../../static/images/icon-record-five.png" alt="">
                  <div>安全检查</div>                
                </div>
                <div>
                  <img src="../../static/images/icon-record-down.png" alt="" v-show="isShow2 === false">
                  <img src="../../static/images/icon-record-up.png" alt="" v-show="isShow2 === true">
                </div>
              </div>
              <div class="count" v-show="isShow2 === true">
                <div class="info">
                  <div class="name">检查频次数</div>
                  <div class="value">{{ addStrongObj.inspectTimes }}</div>
                </div>
                <div class="info">
                  <div class="name">检查落实数</div>
                  <div class="value">{{ addStrongObj.inspectPraTimes }}</div>
                </div>
                <div class="info">
                  <div class="name">闸坝问题数</div>
                  <div class="value">{{ addStrongObj.damIssues }}</div>
                </div>
              </div>
            </div> 
            <div class="record">
              <div class="item" @click.prevent="showToast('暂无数据')">
                <div class="name">
                  <img src="../../static/images/icon-record-one.png" alt="">
                  <div>隐患跟踪处理</div>
                </div>
                <div><img src="../../static/images/icon-record-arrow.png" alt=""></div>
              </div>
            </div>                        
            <div class="record">
              <div class="item" @click="isShow1 = !isShow1">
                <div class="name">
                  <img src="../../static/images/icon-record-four.png" alt="">
                  <div>除险加固记录</div>                
                </div>
                <div>
                  <img src="../../static/images/icon-record-down.png" alt="" v-show="isShow1 === false">
                  <img src="../../static/images/icon-record-up.png" alt="" v-show="isShow1 === true">
                </div>
              </div>
              <div class="count" v-show="isShow1 === true">
                <div class="info">
                  <div class="name">风险预警数</div>
                  <div class="value">{{ addStrongObj.alarmNum }}</div>
                </div>
                <div class="info">
                  <div class="name">加固次数</div>
                  <div class="value">{{ addStrongObj.strongTimes }}</div>
                </div>
                <div class="info">
                  <div class="name">风险消除数</div>
                  <div class="value">{{ addStrongObj.disAlert }}</div>
                </div>
              </div>
            </div>                       
          </div>
        </van-tab> -->
        <van-tab title="水位变化统计">         
          <!-- <div class="history">
            <div class="item" style="margin-right: 8px;">
              <div class="title">历史最高水位</div>
              <div class="value">{{ highData && highData.waterLevel || '--' }}m</div>
              <div class="info">监测点：{{ highData && highData.name || '--' }}</div>
              <div class="info">时间：{{ highData && highData.logDate || '--' }}</div>
            </div>
            <div class="item">
              <div class="title">历史最低水位</div>
              <div class="value">{{ lowData && lowData.waterLevel || '--' }}m</div>
              <div class="info">监测点：{{ lowData && lowData.name || '--' }}</div>
              <div class="info">时间：{{ lowData && lowData.logDate || '--' }}</div>
            </div>
          </div>       -->
          <div class="date">
            <van-cell-group>
              <van-field 
                v-model="waterLevelDate" 
                is-link
                arrow-direction="down"
                readonly
                label="水位日期："
                placeholder="请选择日期" 
                @click="showWaterLevelDateFn()"
              />
            </van-cell-group>
            <van-calendar v-model:show="showWaterLevelDate" @confirm="onConfirmWaterLevelDate" :min-date="new Date(2000, 0, 1)" :max-date="new Date()" />
          </div>      
          <div class="content"> 
            <div class="title">水位情况</div>                     
            <div id="lineChart2" style="height: 200px;"></div>
          </div>
        </van-tab>
        <van-tab title="视频监控" v-if="videoDirectoryData.length">
          <van-field
            v-model="videoPointName"
            is-link
            arrow-direction="down"
            readonly
            :disabled="videoDirectoryData.length === 0? true : false"
            label="视频点："
            placeholder="请选择视频点"
            @click="showVideoPoint = true"
            style="margin-top: 16px;"
          />
          <van-popup v-model:show="showVideoPoint" round position="bottom">
            <van-picker
              title="选择视频点"
              :columns="videoDirectoryData"
              :columns-field-names="videoPointFieldName"
              @cancel="showVideoPoint = false"
              @confirm="confirmVideoPoint"
            />
          </van-popup>
          <div class="no-data" v-if="videoDirectoryData.length === 0">
            <img src="../../static/images/icon-no-data.png" alt="">
            <div>暂无数据</div>
          </div>     
          <div class="video" style="height: 200px;margin: 16px;" v-show="videoDirectoryData.length">
            <video 
              id="myVideo" 
              class="video-js vjs-default-skin vjs-big-play-centered"         
              style="object-fit: fill;width: 100%;height: 100%;"
            >
            </video>
          </div> 
        </van-tab>
      </van-tabs>
    </div>  
  </div>
</template>

<script setup>
  import { ref, onMounted, nextTick, onUnmounted } from 'vue';

  import { useRouter } from "vue-router";
  const router = useRouter();
  
  import * as echarts from 'echarts/core';
  import { TooltipComponent, GridComponent, LegendComponent, DataZoomComponent } from 'echarts/components';
  import { PieChart, BarChart, LineChart } from 'echarts/charts';
  import { UniversalTransition } from 'echarts/features';
  import { CanvasRenderer } from 'echarts/renderers';
  echarts.use([TooltipComponent, GridComponent, LegendComponent, DataZoomComponent, PieChart, BarChart, LineChart, CanvasRenderer, UniversalTransition]);

  import videojs from 'video.js';
  import 'video.js/dist/video-js.css';
  import VideojsZhcnLanguage from 'video.js/dist/lang/zh-CN.json';
  videojs.addLanguage('zh-CN',VideojsZhcnLanguage);

  // 引入api
  import {
    getShipLock, //获取船闸列表
    baseInfo, //基本信息
    goodsTonAlys, //过闸船舶货物吨位统计分析
    goodsAnalysis, //过闸船舶货物类型统计分析
    addStrong, //除险加固记录、安全检查
    waterAlys, //水位变化统计分析
    getCycList, //获取周期
    defAyls, //多点单周期图
    defSingleAyls, //单点多周期图
    theHighLow, //历史水位
    videoDirectory, //获取视频点
    geVideotUrl, //获取视频URL
  } from "@/bridge-h5/utils/myapi";

  import { showToast } from "vant";

  //获取船闸
  const shipLock = ref('');
  const shipLockOptions = ref([]);
  const customFieldName = {
    text: 'name',
    value: 'name',
  };
  const getShipLockFunction = () => {
    getShipLock("北江").then((res) => {
      if(res.code === 200 && res.data.length){
        shipLockOptions.value = res.data;
        shipLock.value = res.data[1].name;
        baseInfoFunction();     
        isShowVideoMoudle();
      }
    });
  };
  const showPicker = ref(false);
  const confirmShipLock = ({ selectedOptions }) => {
    showPicker.value = false;
    shipLock.value = selectedOptions[0].name === "全部"? "" : selectedOptions[0].name;
    isShowVideoMoudle();

    let currentTab = tabActive.value;
    if(currentTab === 0){
      baseInfoFunction();   
    }else if(currentTab === 1){
      initStackedChart();
      initPieChart();
    }else if(currentTab === 2){
      theHighLowFn();
      initLineChart2();
    }else if(currentTab === 3){
      videoDirectoryFunction();
    }        
  };

  //基本信息
  const baseInfoObj = ref({});
  const baseInfoFunction = () => {
    baseInfo(shipLock.value).then((res) => {
      if(res.code === 200 && res.data){
        baseInfoObj.value = res.data;
      }
    });
  };

  const tabActive = ref(0);
  const onClickTab = ({ title }) => {
    if(title === "变形监测分析"){
      currentActive.value = 1;
      getCycListFunction();
    }else if(title === "闸坝情况记录"){
      addStrongFunction();
    }else if(title === "水位变化统计"){
      theHighLowFn();
      initLineChart2();
    }else if(title === "过闸船舶统计分析"){
      initStackedChart();
      initPieChart();
    }else if(title === "视频监控"){
      initVideo();
    }
  };

  //日期
  const date1 = ref('');
  const showCalendar1 = ref(false);
  const confirmDate1 = (values) => {
    const [start, end] = values;
    date1.value = new Date(start).format('yyyy-MM-dd') + '~' + new Date(end).format('yyyy-MM-dd');
    initStackedChart();
    initPieChart();
    showCalendar1.value = false;
  };

  const year = ref(new Date().format("yyyy"));
  const currentDate = ref([new Date().format("yyyy")]);
  const columnsType = ['year'];
  const showYearPicker = ref(false);
  const confirmYear = (val) => {
    year.value = val.selectedValues[0];
    initStackedChart();
    showYearPicker.value = false;
  };
  //过闸船舶货物吨位统计
  const totalUpShipNum = ref(0);
  const totalDownShipNum = ref(0);
  const initStackedChart = () => {
    // let start = date1.value.split('~')[0];
    // let end = date1.value.split('~')[1];
    goodsTonAlys(
      shipLock.value, 
      `${year.value}-01-01`, 
      `${year.value}-12-31`
    ).then((res) => {
      if(res.code === 200 && res.data){
        totalUpShipNum.value = res.data.totalUpShipNum;
        totalDownShipNum.value = res.data.totalDownShipNum;
        let emptyData = [];
        let num1Data = [];
        let num2Data = [];
        let num3Data = [];
        let num4Data = [];
        let upShipNumData = [];
        let downShipNumData = [];
        res.data.tons.forEach((item) => {
          emptyData.push(item.empty);
          num1Data.push(item.num1);
          num2Data.push(item.num2);
          num3Data.push(item.num3);
          num4Data.push(item.num4);
          upShipNumData.push(item.upShipNum);
          downShipNumData.push(item.downShipNum);
        });

        nextTick(() => {        
          let stackedChart = echarts.getInstanceByDom(document.getElementById("stackedChart"));
          if(stackedChart != null && stackedChart != "" && stackedChart != undefined){
            stackedChart.dispose();
          }
          stackedChart = echarts.init(document.getElementById('stackedChart'));
          let option;
          option = {
            tooltip: {
              trigger: 'axis',
              confine: true, //限制在图表区域内
              formatter: (params) => {
                // console.log(params)
                let template = `<b>${params[0].axisValue}</b><br>` + `上行船舶数<b style="float:right;padding-left: 20px;">${upShipNumData[parseInt(params[0].axisValue.split('月')[0])-1]}艘</b><br>下行船舶数<b style="float:right;padding-left: 20px;">${downShipNumData[parseInt(params[0].axisValue.split('月')[0])-1]}艘</b><br>`; 
                let count = 0;      
                for(let i = 0; i < params.length; i++){              
                  let item = params[i];   
                  template += item.marker + item.seriesName + `<b style="float:right;padding-left: 20px;">${item.value}艘</b><br>`;    
                  count += item.value;                      
                }  
                return template + `<b style="position: absolute;top: 10px; right: 10px;">总共：${count}艘</b>`;
              },  
            },
            legend: {    
              type: 'scroll',      
            },
            grid: {
              top: '60px',
              left: '50px',
              right: '20px',
              bottom: '30px',
            },
            xAxis: [
              {
                type: 'category',
                axisLabel: {
                  interval:0, 
                },
                data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
              }
            ],
            yAxis: [
              {
                type: 'value',
                name: '船舶数（艘）',
                // axisLabel: {
                //   color: "#FFFFFF"
                // },
                // splitLine: {
                //   lineStyle: {
                //     type: 'dashed',
                //     color: '#20535c'
                //   }
                // } 
              }
            ],          
            series: [
              {
                name: '空载',
                type: 'bar',
                stack: 'Search Engine',
                barWidth: "15%",
                // showBackground: true,
                emphasis: {
                  //折线图的高亮状态。
                  focus: 'series'
                },
                data: emptyData
              },
              {
                name: '0-500吨',
                type: 'bar',
                stack: 'Search Engine',
                barWidth: "15%",
                // showBackground: true,
                emphasis: {
                  focus: 'series'
                },
                data: num1Data
              },
              {
                name: '500-1000吨',
                type: 'bar',
                stack: 'Search Engine',
                barWidth: "15%",
                // showBackground: true,
                emphasis: {
                  focus: 'series'
                },
                data: num2Data
              },
              {
                name: '1000-3000吨',
                type: 'bar',
                stack: 'Search Engine',
                barWidth: "15%",
                // showBackground: true,
                emphasis: {
                  focus: 'series'
                },
                data: num3Data
              },
              {
                name: '3000吨以上',
                type: 'bar',
                stack: 'Search Engine',
                barWidth: "15%",
                // showBackground: true,
                emphasis: {
                  focus: 'series'
                },
                data: num4Data
              }
            ]
          };

          option && stackedChart.setOption(option);
        });
      }
    });    
  };

  //过闸船舶货物类型统计分析
  const pieChartData = ref([]);
  const initPieChart = () => {
    let start = date1.value.split('~')[0];
    let end = date1.value.split('~')[1];
    goodsAnalysis(shipLock.value, start, end).then((res) => {
      if(res.code === 200){  
        let seriesData = [];     
        let colorData = [
          '#6B9BFD','#af71db','#ffa257','#135ddf','#0e8a89','#ffcb32','#4ed9a0','#67cdf7','#67c577','#13cdff',
          '#91cc75','#99cdff','#10757C','#C8778E','#D4B6F4','#8F7059','#EDD18C','#CA3F54','#01448B','#165dff',
          '#FFFF33','#B22222','#FFB6C1','#4B0082','#DDA0DD','#E6E6FA','#F08080','#483D8B','#40E0D0','#330033', 
          '#996666','#996699','#EE0000','#6666FF','#660099','#666699','#0000FF','#FF9933','#CC33CC','#003333',               
        ]; 
        res.data.forEach((item,index) => {
          let obj = {
            name: item.cargoType,
            value: item.rate,
            load: item.load,
            itemStyle: { 
              color: colorData[index]
            }
          };
          seriesData.push(obj);
        });
        pieChartData.value = seriesData;
        let pieChart = echarts.getInstanceByDom(document.getElementById("pieChart"));
        if(pieChart != null && pieChart != "" && pieChart != undefined){
          pieChart.dispose();
        }
        pieChart = echarts.init(document.getElementById('pieChart'));
        let option;
        option = {
          tooltip: {
            trigger: 'item',
            confine: true, //限制在图表区域内
            formatter: function (params) {
              return params.marker + params.data.name + ': ' + params.data.load + '吨，占比：' + params.data.value + '%'
            },    
          },
          legend: {   
            type: 'scroll',          
            // textStyle: {
            //   color: '#0ACCCC'
            // }
          },
          series: [
            {
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              label: {
                show: false,
                position: 'center'
              },
              data: seriesData
            }
          ]
        };
        option && pieChart.setOption(option);
      }
    });    
  };

  //变形监测分析
  const currentActive = ref(1);
  const currentActiveChange = (val) => {
    currentActive.value = val;
    singleType.value = "周期";
    if(val === 1){
      defAylsFunction();
    }else{
      defSingleAylsFunction();
    }
  };
  const cycle = ref('');
  const showTypePicker = ref(false);
  const singleType = ref('周期');
  const singleTypeData = [
    { text: '周期', value: '周期' },
    { text: '时间', value: '时间' },
  ];
  const confirmType = ({ selectedOptions }) => {
    showTypePicker.value = false;
    singleType.value = selectedOptions[0].value;
    defSingleAylsFunction();
  };
  const singleValue1 = ref('');
  const singleValue2 = ref('');  
  const cycleOptions = ref([]);
  const showCyclePicker = ref(false);
  const cycleFieldName = {
    text: 'cycName',
    value: 'cycName',
  };
  const currentCycle = ref('');
  const showCycle = (type) => {
    if(!cycleOptions.value.length){
      showToast("暂无数据");
      return;
    }
    currentCycle.value = type;
    showCyclePicker.value = true;
  };
  const confirmCycle = ({ selectedOptions }) => {
    showCyclePicker.value = false;
    if(currentCycle.value === 'cycle'){
      cycle.value = selectedOptions[0].cycName;
      defAylsFunction();
    }else if(currentCycle.value === 'singleValue1'){
      singleValue1.value = selectedOptions[0].cycName;
      defSingleAylsFunction();
    }else if(currentCycle.value === 'singleValue2'){
      singleValue2.value = selectedOptions[0].cycName;
      defSingleAylsFunction();
    }        
  };
  const pointName = ref('');
  const pointNameData = ref([]);
  const showPointPicker = ref(false);
  const confirmPoint = ({ selectedOptions }) => {
    showPointPicker.value = false;
    pointName.value = selectedOptions[0].value;
    defSingleAylsFunction();
  };
  const singleTime = ref('');
  const showCalendar = ref(false);
  const onConfirmCalendar = (values) => {
    const [start, end] = values;
    singleTime.value = new Date(start).format('yyyy-MM-dd') + '~' + new Date(end).format('yyyy-MM-dd');
    showCalendar.value = false;
    defSingleAylsFunction();
  };
  const getCycListFunction = () => {
    getCycList(shipLock.value).then((res) => {
      if(res.code === 200){
        res.data.forEach((item) => {
          item.cycName = `第${item.cyc}周期`;
        }); 
        cycleOptions.value = res.data;
        if(res.data.length){
          cycle.value = res.data[0].cycName;
          singleValue1.value = res.data[0].cycName;
          singleValue2.value = res.data[0].cycName;          
        }else{
          cycle.value = "";
          singleValue1.value = "";
          singleValue2.value = "";
        }  
        defAylsFunction();
      }
    });
  };
  const aylsXAxisData = ref([]);
  const aylsSeriesData = ref([]);
  const defAylsFunction = () => {
    defAyls(shipLock.value, cycle.value.replace('第','').replace('周期','')).then((res) => {
      if(res.code === 200){
        if(res.data.length){
          let nData = [];
          let eData = [];
          let zData = [];
          pointNameData.value = [];
          aylsXAxisData.value = [];
          res.data.forEach((item) => { 
            pointNameData.value.push(
              { text: item.pointName, value: item.pointName }              
            );
            aylsXAxisData.value.push(item.pointName);
            nData.push(item.acDn);
            eData.push(item.acDe);
            zData.push(item.acDz);
          });
          pointName.value = pointNameData.value[0].value;
          aylsSeriesData.value = [
            {
              name: '累积变化量N',
              type: 'line',
              smooth: true,
              data: nData
            },
            {
              name: '累积变化量E',
              type: 'line',
              smooth: true,
              data: eData
            },
            {
              name: '累积变化量Z',
              type: 'line',
              smooth: true,
              data: zData
            }
          ];
          initLineChart1();
        }else{
          pointNameData.value = [];
          pointName.value = "";

          aylsXAxisData.value = [];
          aylsSeriesData.value = [];
          initLineChart1();
        }      
      }
    });
  };
  const defSingleAylsFunction = () => {
    defSingleAyls(
      singleType.value === '周期'? singleValue1.value.replace('第','').replace('周期','') : singleTime.value.split('~')[0], 
      singleType.value === '周期'? singleValue2.value.replace('第','').replace('周期','') : singleTime.value.split('~')[1], 
      singleType.value === '周期'? 1 : 2, 
      pointName.value, 
      shipLock.value
    ).then((res) => {
      if(res.code === 200){
        let nData = [];
        let eData = [];
        let zData = [];
        aylsXAxisData.value = [];
        res.data.forEach((item) => {
          if(singleType.value === 2){
            aylsXAxisData.value.push(item.createTime);
          } else {
            aylsXAxisData.value.push(item.cyc);
          }         

          nData.push(item.acDn);
          eData.push(item.acDe);
          zData.push(item.acDz);
        });
        aylsSeriesData.value = [
          {
            name: '累积变化量N',
            type: 'line',
            smooth: true,
            data: nData
          },
          {
            name: '累积变化量E',
            type: 'line',
            smooth: true,
            data: eData
          },
          {
            name: '累积变化量Z',
            type: 'line',
            smooth: true,
            data: zData
          }
        ];
        initLineChart1();
      }
    });
  };
  const initLineChart1 = () => {
    nextTick(() => {
      let lineChart = echarts.getInstanceByDom(document.getElementById("lineChart1"));
      if(lineChart != null && lineChart != "" && lineChart != undefined){
        lineChart.dispose();
      }
      lineChart = echarts.init(document.getElementById('lineChart1'));
      let option;
      option = {
        grid: {
          top: '35px',
          left: '40px',
          right: '15px',
          bottom: '40px',
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['累积变化量N', '累积变化量E', '累积变化量Z'],
          textStyle: {
            color: 'rgba(0,0,0,0.8)'
          },
        },
        xAxis: {
          type: 'category',
          data: aylsXAxisData.value,
          axisLabel: {
            color: "#595959"
          } 
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: "#595959"
          },
          splitLine: {
            show: true,
            lineStyle:{
              // type:'dashed',
              color: '#F0F0F0'
            }
          } 
        },
        series: aylsSeriesData.value
      };

      option && lineChart.setOption(option);
    });
  };

  //闸坝情况记录
  const isShow1 = ref(false);
  const isShow2 = ref(false);
  //除险加固记录、安全检查
  const addStrongObj = ref({});
  const addStrongFunction = () => {
    addStrong(shipLock.value).then((res) => {
      if(res.code === 200 && res.data){
        addStrongObj.value = res.data;
      }
    });
  }
  const handleGo = () => {
    router.push({
      path: "/lockRecord",
      query: {},
    });
  };

  //历史水位
  const highData = ref({});
  const lowData = ref({});
  const theHighLowFn = () => {
    theHighLow(shipLock.value).then((res) => {
      if(res.code === 200){
        highData.value = res.data.high;
        lowData.value = res.data.low;
      }
    });
  };

  //水位变化统计
  const waterLevelDate = ref('');
  const showWaterLevelDate = ref(false);
  const showWaterLevelDateFn = () => {
    showWaterLevelDate.value = true;
    //隐藏echarts tooltip
    let lineChart = echarts.getInstanceByDom(document.getElementById("lineChart2"));
    lineChart.dispatchAction({
      type: 'hideTip'
    });
  };
  const onConfirmWaterLevelDate = (value) => {
    showWaterLevelDate.value = false;
    waterLevelDate.value = new Date(value).format('yyyy-MM-dd');
    initLineChart2();
  };
  const initLineChart2 = () => {
    nextTick(() => {
      waterAlys(shipLock.value, waterLevelDate.value).then((res) => {
        if(res.code === 200){        
          let xAxisData = [];
          let seriesData = [];
          res.data.forEach((item) => {
            xAxisData.push(item.logDate.slice(11,16));          
            seriesData.push(item.waterLevel);
          });
          let lineChart = echarts.getInstanceByDom(document.getElementById("lineChart2"));
          if(lineChart != null && lineChart != "" && lineChart != undefined){
            lineChart.dispose();
          }
          lineChart = echarts.init(document.getElementById('lineChart2'));
      
          let option;
          option = {
            tooltip: {
              trigger: 'axis',
              confine: true, //限制在图表区域内
              formatter: function (params) {
                let template = `${params[0].axisValue}<br>`;         
                for(let i = 0; i < params.length; i++){
                  let item = params[i];
                  template += item.marker + '水位值: ' + item.value + 'm' + '<br>'
                  // return params[x].data.name + ':' + params[x].data.value
                }  
                return template  
              },
            },
            grid: {
              top: '40px',
              left: '40px',
              right: '12%',
              bottom: '45px',
            },
            dataZoom: [
              {
                show: false,
                type: "inside",
                startValue: 0,
                endValue: 11,
                zoomLock: false,
              },
            ],
            xAxis: {
              type: 'category',
              name: '时间',
              data: xAxisData,  
              axisLabel: {
                interval:0, 
                rotate: 60,
              },               
            },
            yAxis: {
              type: 'value',
              name: '水位（m）',
            },
            series: [
              {
                data: seriesData,
                type: 'line',
                
              }
            ],
          };
          option && lineChart.setOption(option);           
        }
      });  
    });
  };

  //视频监控  
  const myPlayer = ref(null);
  const initVideo = () => {
    nextTick(() => { 
      myPlayer.value = videojs("myVideo",{
        language: 'zh-CN',  //汉化
        autoplay: true, // true,浏览器准备好时开始播放
        loop: true, // 导致视频一结束就重新开始
        controls: true, //取消视频中的进度条
        muted: true, //是否静音
        preload: 'metadata', //auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）      
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 无法播放媒体源时显示的默认信息
        textTrackDisplay: false,
        techOrder: ['html5', 'flash']
      }); 
    });
    videoDirectoryFunction();
  };   
  const showVideoPoint = ref(false);
  const videoDirectoryData = ref([]);
  const videoPoint = ref('');
  const videoPointName = ref('');
  const videoPointFieldName = {
    text: 'name',
    value: 'id',
  };
  const confirmVideoPoint = ({ selectedOptions }) => {
    console.log(selectedOptions)
    videoPoint.value = selectedOptions[0].id;
    videoPointName.value = selectedOptions[0].name;
    showVideoPoint.value = false;
    geVideotUrlFunction();
  };
  const videoDirectoryFunction = () => {
    videoDirectory(shipLock.value).then((res) => {
      if(res.code === 200 && res.data.length){
        videoDirectoryData.value = res.data;
        videoPoint.value = res.data[0].id;
        videoPointName.value = res.data[0].name;        
        geVideotUrlFunction();
      }else{
        videoDirectoryData.value = [];
        videoPoint.value = "";   
        videoPointName.value = "";   
      }
    });
  };
  const geVideotUrlFunction = () => {
    geVideotUrl(videoPoint.value).then((res) => {
      if(res.code === 200 && res.data){
        // const myPlayer = videojs("myVideo"); 
        myPlayer.value.src([
          {
            type: 'application/x-mpegURL',
            src: res.data.url, //视频播放地址
          }
        ]); 
        myPlayer.value.play();
      }
    });
  };  
  const isShowVideoMoudle = () => {
    videoDirectory(shipLock.value).then((res) => {
      if(res.code === 200 && res.data.length){
        videoDirectoryData.value = res.data;
      }else{
        tabActive.value = 0;
        videoDirectoryData.value = [];
        setTimeout(() => {
          // const myPlayer = videojs("myVideo");    
          if(myPlayer.value){
            myPlayer.value.dispose();
          }   
        }, 300); 
      }
    });
  };

  onMounted(() => {
    singleTime.value = new Date().format('yyyy-MM-dd') + '~' + new Date().format('yyyy-MM-dd');
    waterLevelDate.value = new Date().format('yyyy-MM-dd');
    date1.value = new Date().format('yyyy-MM-dd') + '~' + new Date().format('yyyy-MM-dd');
    getShipLockFunction();    
  });

  onUnmounted(() => {
    setTimeout(() => {
      // const myPlayer = videojs("myVideo");    
      if(myPlayer.value){
        myPlayer.value.dispose();
      }   
    }, 300);   
  });
</script>

<style lang="scss" scoped>
  .container{
    width: 100%;
    height: 100%;
    .header{
      background-color: #fff;       
      .selected{
        padding: 8px 16px 4px 16px;
        :deep(.van-field){
          box-shadow: 0px 1px 8px 0px rgba(38,111,232,0.08);
          border-radius: 2px;
        }
      }          
    }
    .tab{
      .basic-info{
        margin: 16px;
        background: #FFFFFF;
        box-shadow: 0px 4px 8px 2px rgba(0,0,0,0.08);
        border-radius: 8px;
        .item{
          display: flex;
          font-size: 16px;            
          color: rgba(0,0,0,0.85);
          // text-align: center;
          padding: 12px;
          // &:nth-child(odd){
          //   background-color: rgba(45,120,237,0.1);
          //   .name{
          //     border-right: 1px solid #fff;
          //   }
          // }
          .name{
            width: 40%;
            font-weight: 400;
            font-size: 14px;
            color: #595959;
          }
          .value{
            width: 60%;
            font-weight: 500;
            font-size: 14px;
            color: #262626;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            text-align: right;
          }
        }
      }
      .content{
        margin: 16px;
        background: #FFFFFF;
        box-shadow: 0px 4px 8px 2px rgba(0,0,0,0.08);
        border-radius: 8px;   
        .title{
          font-size: 16px;
          font-weight: bold;
          color: rgba(0,0,0,0.85);
          padding: 8px 0px 8px 16px;
          background: rgba(22,93,255,0.05);
          box-shadow: 0px 1px 0px 0px rgba(0,0,0,0.1);
        }
        .filter{
          display: flex;
          padding: 8px;
        }     
        .record{
          margin: 0 8px;
          padding: 8px 0;
          border-bottom: 1px solid rgba(0,0,0,0.2);
          &:last-child{
            border-bottom: none;
          }
          .item{
            display: flex;
            justify-content: space-between;
            align-items: center;
            .name{
              display: flex;
              align-items: center;
              font-size: 16px;
              // font-weight: bold;
              color: rgba(0,0,0,0.85);           
              img{
                width: 20px;
                height: 20px;
                padding-right: 8px;
              }
            }
          }
          .count{
            display: flex;
            justify-content: space-between;
            margin-top: 16px;
            padding: 0 8px;
            .info{   
              width: 100%;          
              text-align: center;
              .name{
                background-color: #F7F7F7;
                padding: 4px 0;
                color: #262626;
                font-weight: bold;
              }  
              .value{
                font-size: 16px;
                font-weight: bold;
                color: #266FE8;
                padding-top: 4px;
              }            
            }
          }
        }   
        .count{
          display: flex;
          justify-content: space-around;
          margin-top: 8px;
          .item{
            display: flex;
            align-items: center;
            .name{
              font-size: 12px;
              font-weight: 500;
              color: rgba(0,0,0,0.85);
            }
            .value{
              font-size: 18px;
              font-weight: bold;
              color: #3177EC;
              padding-left: 12px;
            }
          }
        }     
        .pie-table {
          margin: 0 16px;
          padding-bottom: 80px;
          .pie-tbody {
            font-size: 14px;
            font-weight: 500;
            color: #595959;
            .pie-tr {
              display: flex;
              align-items: center;
              justify-content: space-between;
              .li{
                width: 8px;
                height: 8px;
                border-radius: 0px 0px 0px 0px;
                opacity: 1;
                border-radius: 50%;
                margin-right: 6px;
              }
            }
          }
        }  
      }
      .btn-group{
        display: flex;
        margin-left: 16px;
        // justify-content: space-around;
        .btn{
          margin-top: 16px;
          padding: 8px 24px;
          background-color: #F7F7F7;
          border-radius: 8px;    
          color: #565656;        
        }
        .active{
          color: #fff;
          background-color: #165DFF;
        }
      }
      .date{
        margin: 16px;
      }
      .no-data{
        font-size: 16px;
        color: #BBBBBB;
        text-align: center;
        margin-top: 40%;       
      }
      .history{
        margin: 16px;
        display: flex;
        .item{
          width: 50%;
          border-radius: 2px;
          background-color: rgba(242, 247, 255, 1);
          color: rgba(16, 16, 16, 1);
          box-shadow: 0px 0px 6px 0px rgba(174, 174, 174, 0.4);
          text-align: center;
          .title{
            font-size: 14px;
            color: rgba(0, 0, 0, 1);
            padding-top: 10px;
          }
          .value{
            color: rgba(38, 111, 232, 1);
            font-size: 26px;
            font-weight: bold;
            padding: 5px 0;
          }
          .info{
            color: rgba(153, 153, 153, 1);
            font-size: 12px;
            padding-bottom: 5px;
          }
        }
      }
    } 
  }
</style>